package com.haoshui.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.haoshui.constants.RedisCacheConstans;
import com.haoshui.domain.ResponseResult;
import com.haoshui.domain.dto.ArticleDto;
import com.haoshui.domain.entity.Article;
import com.haoshui.domain.vo.ArticleListSysVo;
import com.haoshui.domain.vo.ArticleSysDetailVo;
import com.haoshui.domain.vo.PageVo;
import com.haoshui.enums.AppHttpCodeEnum;
import com.haoshui.service.ArticleService;
import com.haoshui.service.ArticleTagService;
import com.haoshui.utils.BeanCopyUitls;
import com.haoshui.utils.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
public class ArticleContrroller {

    @Autowired
    private ArticleService articleService;

    @Autowired
    private ArticleTagService articleTagService;

    @Autowired
    private RedisCache redisCache;

    /**
     * 添加文章
     * @param articleDto
     * @return
     */
    @PostMapping("/content/article")
    public ResponseResult addArticle(@RequestBody ArticleDto articleDto){
        //把文章添加到数据库
       Long articleId = articleService.addArticle2(articleDto);



        if(articleId == -1){
            return ResponseResult.errorResult(AppHttpCodeEnum.INSERT_FAILED);
        }

        //把文章的浏览量添加到redis中
        Map<String, Integer> article = new HashMap<>();
        article.put(articleId.toString(), 0);
        redisCache.setCacheMap(RedisCacheConstans.VIEW_COUNT_KEY_IN_REDIS,article);

        return ResponseResult.okResult();
    }


    /**
     * 根据文章名或者摘要查询文章，或者分页查询
     * @param pageNum
     * @param pageSize
     * @param title
     * @param summary
     * @return
     */
    @GetMapping("/content/article/list")
    @PreAuthorize("@ps.hasPermission('content:article:list')")
    public ResponseResult listArticle(Integer pageNum, Integer pageSize, String title, String summary){
        //获取文章列表
        Page<Article> articles =  articleService.findArticle(pageNum, pageSize, title, summary);

        //封装成ArticleListSysVo
        List<ArticleListSysVo> articleListSysVos = BeanCopyUitls.copyBeanList(articles.getRecords(), ArticleListSysVo.class);

        //封装成PageVo
        PageVo pageVo = new PageVo(articleListSysVos, articles.getTotal());

        //封装响应返回
        return ResponseResult.okResult(pageVo);
    }

    /**
     * 修改某篇文章，先查询此文章的信息
     * @param id
     * @return
     */
    @GetMapping("content/article/{id}")
    @PreAuthorize("@ps.hasPermission('content:article:list')")
    public ResponseResult getArticle(@PathVariable("id") Long id){
        //获得文章的基本信息
        Article article =  articleService.getArticle(id);

        //封装成ArticleSysDetailVo
        ArticleSysDetailVo vo = BeanCopyUitls.copyBean(article, ArticleSysDetailVo.class);

        //查找tagsId
        List<Long> tags =  articleTagService.getTagIdsByArticleId(id);

        //存tags到ArticleSysDetailVo中
        List<String> collect = tags.stream().map(tag -> tag.toString()).collect(Collectors.toList());
        vo.setTags(collect);

        return ResponseResult.okResult(vo);

    }


    /**
     * 修改某篇文章，具体的修改接口
     * @param articleSysDetailVo
     * @return
     */
    @PutMapping("content/article")
    @PreAuthorize("@ps.hasPermission('content:article:list')")
    public ResponseResult updateArticle(@RequestBody ArticleSysDetailVo articleSysDetailVo){
        //从中取出Article
        Article article = BeanCopyUitls.copyBean(articleSysDetailVo, Article.class);

        //更新article表
        boolean resultArticle =   articleService.updateArticle(article);

        //TODO tag和article的更新应该同步

        //更新article和 tag的映射关系
        boolean resultTag = articleTagService.updateTags(article.getId(), articleSysDetailVo.getTags());

        if(resultTag && resultArticle){
            return ResponseResult.okResult();
        }else{
            return ResponseResult.errorResult(AppHttpCodeEnum.UPDATE_FAILED);
        }
    }


    /**
     * 逻辑删除一篇文章
     * @param id
     * @return
     */
    @DeleteMapping("content/article/{id}")
    @PreAuthorize("@ps.hasPermission('content:article:list')")
    public ResponseResult deleteArticle(@PathVariable("id") Long id){
        //删除文章操作
        boolean b = articleService.removeById(id);

        //TODO 或许ArticleTag表也需要删除

        if(b){
            return  ResponseResult.okResult();
        }else{
            return ResponseResult.errorResult(AppHttpCodeEnum.DELETE_FAILED);
        }
    }



}
